package com.icebergteam.warfacewidget.ui;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import org.jsoup.Jsoup;
import com.icebergteam.warfacewidget.AppManager;
import com.icebergteam.warfacewidget.R;
import com.icebergteam.warfacewidget.WidgetApplication;
import com.icebergteam.warfacewidget.WidgetProvider;
import com.icebergteam.warfacewidget.core.ListViewItem;
import com.icebergteam.warfacewidget.core.LogManager;
import com.icebergteam.warfacewidget.core.Parser;
import com.icebergteam.warfacewidget.core.ParserException;
import com.icebergteam.warfacewidget.data.sql.RankTable;
import com.icebergteam.warfacewidget.data.sql.UserRankTable;
import com.icebergteam.warfacewidget.news.ui.NewsActivity;
import com.icebergteam.warfacewidget.rank.data.Top100ClansItem;
import com.icebergteam.warfacewidget.rank.data.Top100ClansParser;
import com.icebergteam.warfacewidget.rank.data.Top100Item;
import com.icebergteam.warfacewidget.rank.data.Top100Parser;
import com.icebergteam.warfacewidget.rank.data.TopUsersItem;
import com.icebergteam.warfacewidget.rank.data.TopUsersParser;
import com.icebergteam.warfacewidget.rank.ui.Top100ClansModelAdapter;
import com.icebergteam.warfacewidget.rank.ui.Top100ModelAdapter;
import com.icebergteam.warfacewidget.rank.ui.TopUsersModelAdapter;
import com.icebergteam.warfacewidget.core.asynctaskmanager.AsyncTaskManager;
import com.icebergteam.warfacewidget.core.asynctaskmanager.IHandleMessage;
import com.icebergteam.warfacewidget.core.asynctaskmanager.IProgressTracker;
import com.icebergteam.warfacewidget.core.asynctaskmanager.Task;
import com.icebergteam.warfacewidget.core.asynctaskmanager.TaskProgress;
import com.icebergteam.warfacewidget.core.connection.NetworkManager;
import com.icebergteam.warfacewidget.core.utils.TimeDateUtils;
import com.icebergteam.warfacewidget.core.utils.ViewUtils;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ShareActionProvider;
import android.widget.Toast;
import android.widget.ShareActionProvider.OnShareTargetSelectedListener;
import android.widget.TextView;

public class RatingActivity extends FragmentActivity implements IHandleMessage,
IProgressTracker, OnShareTargetSelectedListener{
	public static final String className = RatingActivity.class.getCanonicalName();
	
	String[] servers = null;
	String[] categories = null;
	String[] classes = null;
	
	int offsetIndexServer = 1;
	int currentIndexServer =0;
	
	int offsetIndexCategory = 1;
	int currentIndexCategory = offsetIndexCategory;
	
	int offsetIndexClass = 1;
	int currentIndexClass =0;
	
	public static final int TOP_100 = 1;
	public static final int TOP_USERS = 2;
	public static final int TOP_100_CLANS = 3;
	
	private boolean listExpanded = false;
	
	Button serverButton;
	Button categoryButton;
	Button classButton;
	ImageView expandListIndicator;
	
	// Animation
	private static Animation tapFieldAnimation;
	
	ListView ratingListView;
	TextView dateTextView;
	
	String domainLink = "http://wf.mail.ru/dynamic/ajax/index.php?do=get_ladder_info&server=%s&category=%s&subcategory=%s";
	
	private AsyncTaskManager asyncTaskManager;
	
	long stepUpdateTop100RankActivity = 3600000;
	
	public static String LIST_EXPANDED_INTENT = String.format("%s.LIST_EXPANDED_INTENT",
			className);  
	
	public static final String KEY_HEIGHT_ACTION_BAR = String.format(
			"%s.KEY_HEIGHT_ACTION_BAR", className);

	private int heightActionBar = 96;

		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_rating);
		
		// Create manager and set this activity as context and listener
		asyncTaskManager = new AsyncTaskManager(this, this);
		// Handle task that can be retained before
		asyncTaskManager.handleRetainedTask(getLastNonConfigurationInstance());
		
		serverButton		= (Button) findViewById(R.id.rating_activity_server_button);
		categoryButton		= (Button) findViewById(R.id.rating_activity_category_button);
		classButton			= (Button) findViewById(R.id.rating_activity_class_button);
		expandListIndicator	= (ImageView) findViewById(R.id.rating_activity_expand_list_indicator); 
		
		
		
		// You can also just use mPullRefreshListFragment.getListView()
		ratingListView = (ListView) findViewById(R.id.rating_activity_listview);
		ratingListView.setEmptyView(findViewById(R.id.rating_activity_empty_list_view));

			
	
		dateTextView = (TextView) findViewById(R.id.rating_activity_date_textview);
		
		AdBannerFragment.setBanner(this, savedInstanceState, R.id.news_activity_adbanner_layout);
		
		// Prepare animation
		tapFieldAnimation = AnimationUtils.loadAnimation(RatingActivity.this, R.anim.tap_prefs_field);
		tapFieldAnimation.reset();
		
		if(savedInstanceState != null){
			listExpanded = savedInstanceState.getBoolean(RatingActivity.LIST_EXPANDED_INTENT, false);
			this.heightActionBar = savedInstanceState
					.getInt(NewsActivity.KEY_HEIGHT_ACTION_BAR);
		}
		
		load();
	
		rebuildList(false);
		expandList(listExpanded);
	}
	
	@Override
	public Object onRetainCustomNonConfigurationInstance() {
		return asyncTaskManager.retainTask();
	}
		
	void load(){
		AppManager.getTop100Settings().load();
		currentIndexServer = AppManager.getTop100Settings().getCurrentIndexServer();
		currentIndexCategory = AppManager.getTop100Settings().getCurrentIndexCategory();
		currentIndexClass = AppManager.getTop100Settings().getCurrentIndexClass();
		stepUpdateTop100RankActivity = AppManager.getTop100Settings().getStepUpdateTop100RankActivity();
		
		servers = RatingActivity.this.getResources().getStringArray(R.array.servers);
		categories = RatingActivity.this.getResources().getStringArray(R.array.categories);
		LogManager.LogEA(className, categories);
		classes = RatingActivity.this.getResources().getStringArray(R.array.classes_top100);
	}
	
	void rebuildList(final boolean update){
		normalizeCurrentIndexServer();
		normalizeCurrentIndexCategory();
		normalizeCurrentIndexClasses();
		switch(currentIndexCategory){
		case TOP_100:
			
			classButton.setText(String.format("%s %s",this.getString(R.string.rating_activity_class_button_text), classes[currentIndexClass]));
			classButton.setVisibility(View.VISIBLE);
			break;
		case TOP_100_CLANS:
			classButton.setVisibility(View.GONE);
			break;
		case TOP_USERS:
			classButton.setVisibility(View.GONE);
			break;
		};
		
		serverButton.setText(String.format("%s %s",this.getString(R.string.rating_activity_server_button_text),  servers[currentIndexServer]));
		categoryButton.setText(String.format("%s %s",this.getString(R.string.rating_activity_category_button_text), categories[currentIndexCategory-offsetIndexCategory]));
		
		this.runOnUiThread(new Runnable() {
			public void run() {
				Top100RequestAsyncTask task = new Top100RequestAsyncTask(new TaskProgress(getString(R.string.wait)), RatingActivity.this, update);
				task.setCancelableTask(false);
				asyncTaskManager.setupTask(task);
				task.execute();
			}
		});
		
		AppManager.getTop100Settings().setCurrentIndexServer(currentIndexServer);
		AppManager.getTop100Settings().setCurrentIndexCategory(currentIndexCategory);
		AppManager.getTop100Settings().setCurrentIndexClass(currentIndexClass);
		AppManager.getTop100Settings().save();
		
	}
	
	View getShareRatingPreview(View contentView, ListViewItem item) throws Exception {
		// Setup layout
		LayoutInflater li = LayoutInflater.from(this);
		View v = li.inflate(R.layout.share_rating_layout, null);
		// Setup rating
		FrameLayout container = (FrameLayout) v.findViewById(R.id.sharing_layout_preview_sharing_content);
		
		switch (currentIndexCategory) {
		case TOP_100:
			container.addView(Top100ModelAdapter.getViewWithParam(RatingActivity.this, null, (Top100Item) item));
			break;
		case TOP_100_CLANS:
			container.addView(Top100ClansModelAdapter.getViewWithParam(RatingActivity.this, null, (Top100ClansItem) item));
			break;
		default:
			throw new Exception(className + " getShareRatingPreview() " + "Error: Undefined category");
		}
		return v;		
	}
	
	public void onClick(View v){
		int idButton = v.getId();
		LogManager.LogVA(className, idButton);
		switch(idButton){
		case R.id.rating_activity_server_button:
			currentIndexServer++;
			startTapFieldAnimation(v);
			rebuildList(false);
			break;
		case R.id.rating_activity_category_button:
			currentIndexCategory ++;
			normalizeCurrentIndexCategory();
			
			switch(currentIndexCategory){
			case TOP_100:
				currentIndexClass = 0;
				break;
			case TOP_100_CLANS:
				currentIndexClass = offsetIndexClass;
				break;
			};
			startTapFieldAnimation(v);			
			rebuildList(false);
			break;
		case R.id.rating_activity_class_button:
			currentIndexClass++;
			startTapFieldAnimation(v);
			rebuildList(false);
			break;
		case R.id.rating_activity_expand_list:
			expandList(!listExpanded);
			break;
		}
		
		LogManager.LogEA(className, currentIndexClass);
	}
	
	class Top100RequestAsyncTask extends /*AsyncTask<String, Integer, Integer>*/Task {
		private boolean needUpdate = false;
		public Top100RequestAsyncTask( TaskProgress message,
				IHandleMessage _handleError, boolean _needUpdate) {
			super(message, _handleError);
			needUpdate = _needUpdate;
		
		}

		private final int CODE_ERROR = 0;
		private final int CODE_OK = 1;
		long date = 0;
		
		public final String className = Top100RequestAsyncTask.class.getCanonicalName();
		
		private void showToast(final String str, final int time){
			RatingActivity.this.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(RatingActivity.this, str, time).show();								
				}
			});
		}

		Object getCursorTop100(Parser parser, String url) throws Exception{
			
			try{
				Cursor cursor = AppManager.getDatabase().getRankTable().getRankByUrl(url);
				if(needUpdate || !cursor.moveToFirst() || (cursor.moveToFirst() && new Date().getTime() - cursor.getLong(cursor.getColumnIndex(RankTable.FIELD_PUBDATE.trim())) > stepUpdateTop100RankActivity)){
					LogManager.LogVA(className, "update");
					
					publishProgress(new TaskProgress(	getString(R.string.responce_from_official_site), 0));
					parser.saveData(url);
					cursor = AppManager.getDatabase().getRankTable().getRankByUrl(url);
					cursor.moveToFirst();
				}
				
				date = cursor.getLong(cursor.getColumnIndex(RankTable.FIELD_PUBDATE.trim()));
				publishProgress(new TaskProgress(getString(R.string.parsing_data), 50));
				return parser.parseXML(Jsoup.parse(cursor.getString(cursor.getColumnIndex(RankTable.FIELD_HTML.trim()))), -1);
				
				
			}
			catch(ParserException e){
				publishProgress(new TaskProgress(getString(R.string.parsing_data), 50));
				switch(e.getStateRequest()){
					case Parser.DB_INVALID:
						showToast(getString(R.string.unknown_error), Toast.LENGTH_LONG);
						break;
					case Parser.XML_INVALID:
						showToast(getString(R.string.unknown_error), Toast.LENGTH_LONG);
						break;
					default:
						Cursor cursor = AppManager.getDatabase().getRankTable().getRankByUrl(url);
						cursor.moveToFirst();
						date = cursor.getLong(cursor.getColumnIndex(RankTable.FIELD_PUBDATE.trim()));
						
						showToast(getString(R.string.restored_complete), Toast.LENGTH_LONG);
						return parser.parseXML(Jsoup.parse(cursor.getString(cursor.getColumnIndex(RankTable.FIELD_HTML.trim()))), -1);
					
				}
					
			}
			return null;
		}
		
		ArrayList<TopUsersItem> getCursorTopUsers(TopUsersParser parser, int server) throws Exception{
			
			try{
				ArrayList<TopUsersItem> listTopUsers = new ArrayList<TopUsersItem>();
				long minDate = AppManager.getDatabase().getUserRankTable().minDate(server);
				if(needUpdate || new Date().getTime() - minDate > stepUpdateTop100RankActivity){
					LogManager.LogVA(className, "update");
					
					publishProgress(new TaskProgress(	getString(R.string.responce_from_official_site), 0));
					
					Cursor cursor = AppManager.getDatabase().getUserRankTable().getRankByServer(server);
										
					while(cursor.moveToNext()){
						int id = cursor.getInt(cursor.getColumnIndex(UserRankTable.FIELD_ID.trim()));
						parser.saveData(String.format("http://warface.eu5.org/get.php?id=%s&server=%s", id, server));
						listTopUsers.add(((TopUsersParser) parser).getTopUsersItem());
					}
					date = new Date().getTime();
				}
				else{
					listTopUsers = AppManager.getDatabase().getUserRankTable().getTopUsersList(server);
					
				}
				
				publishProgress(new TaskProgress(getString(R.string.parsing_data), 50));
				return listTopUsers;
				
				
			}
			catch(ParserException e){
				publishProgress(new TaskProgress(getString(R.string.parsing_data), 50));
				switch(e.getStateRequest()){
					case Parser.DB_INVALID:
						showToast(getString(R.string.unknown_error), Toast.LENGTH_LONG);
						break;
					case Parser.XML_INVALID:
						showToast(getString(R.string.unknown_error), Toast.LENGTH_LONG);
						break;
					default:
						date = AppManager.getDatabase().getUserRankTable().minDate(server);
						showToast(getString(R.string.restored_complete), Toast.LENGTH_LONG);
						
						return AppManager.getDatabase().getUserRankTable().getTopUsersList(server);
					
				}
					
			}
			return null;
		}
		
		@Override
		protected Integer doInBackground(String... params) {
			try {
				final Parser parser;
				final String url = String.format(domainLink, currentIndexServer, currentIndexCategory, currentIndexClass);
				LogManager.LogVA(className, url);
				
				ListAdapter tempAdapter = null;
				LogManager.LogEA(className, currentIndexServer, currentIndexCategory);
				switch(currentIndexCategory){
					case TOP_100:
						parser = new Top100Parser();
														
						tempAdapter = (new Top100ModelAdapter(RatingActivity.this, android.R.layout.simple_list_item_1,  (ArrayList<Top100Item>)getCursorTop100(parser, url)));
						break;
					case TOP_100_CLANS:
						parser = new Top100ClansParser();
						 
						tempAdapter = (new Top100ClansModelAdapter(RatingActivity.this, android.R.layout.simple_list_item_1,  (ArrayList<Top100ClansItem>)getCursorTop100(parser, url)));
						break;
					case TOP_USERS:
						
						parser = new TopUsersParser();
						
						tempAdapter = (new TopUsersModelAdapter(RatingActivity.this, android.R.layout.simple_list_item_1,  getCursorTopUsers( (TopUsersParser) parser, currentIndexServer)));
						
				//		TopUsersParser parser1 = new TopUsersParser("http://warface.eu5.org/get.php?id=123590007&server=1");
				//		parser1.parseXML(NetworkManager.getJSON("http://warface.eu5.org/get.php?id=123590007&server=1"), -1);
						break;
				}
				
				
				
				final ListAdapter adapter = tempAdapter; 
				RatingActivity.this.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						try {
							LogManager.LogEA(className, adapter.getCount());
							dateTextView.setVisibility((adapter.getCount() > 0 )? View.VISIBLE: View.GONE);
							dateTextView.setText(TimeDateUtils.getDateStringFromNormalTimestamp(date, "dd MMM yyyy HH:mm:ss", new Locale(AppManager.getLocaleManager().getCurrentUILangId())));
						
							ratingListView.setAdapter(adapter);
							ratingListView.setOnItemClickListener(new OnItemClickListener() {
	
								@Override
								public void onItemClick(
										AdapterView<?> arg0, final View arg1,
										final int arg2, long arg3) {
								
									AlertDialog.Builder shareDialog = new Builder(RatingActivity.this);
									try {
										final View view = getShareRatingPreview(arg1, (ListViewItem) adapter.getItem(arg2));
										shareDialog
											
											.setMessage(R.string.share_item)
											.setView(view)
											.setIcon(android.R.drawable.ic_dialog_dialer)
											.setPositiveButton(android.R.string.ok, new OnClickListener() {
											
											@Override
											public void onClick(DialogInterface dialog, int which) {
												try {
													ListViewItem listViewItem = ((ListViewItem) adapter.getItem(arg2));

													View row = view;
													row.getDrawingCache(true);
													row.buildDrawingCache();
													Bitmap bm = row.getDrawingCache();
													row.getDrawingCache(false);

													String dir = WidgetProvider.IMG_PATH;
													String imageFilename = String.format("%s.png",listViewItem.getPreviewStr());
													File imageFile = new File(dir, imageFilename);
													OutputStream fos = new FileOutputStream(imageFile);
													BufferedOutputStream bos = new BufferedOutputStream(fos);
													bm.compress(Bitmap.CompressFormat.PNG,100, bos);
													bos.flush();
													bos.close();

													Intent sharingIntent = new Intent(Intent.ACTION_SEND);
													Uri screenshotUri = Uri.parse("file://"+ imageFile.getAbsolutePath());
													sharingIntent.setType("image/png");
													sharingIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share_with_help) + " "+ getString(R.string.app_name));
													sharingIntent.putExtra(	Intent.EXTRA_STREAM, screenshotUri);
													sharingIntent.putExtra(Intent.EXTRA_TEXT, WidgetApplication.MARKET_LINK);
													
													startActivity(Intent.createChooser(sharingIntent, null));
												} catch (FileNotFoundException e) {
													LogManager.LogEA(className, ViewUtils.getErrorMessage(e));
												} catch (IOException e) {
													LogManager.LogEA(className, ViewUtils.getErrorMessage(e));
												}
											}
										})
										.setNeutralButton(android.R.string.no, null)
										.create()
										.show();
									} catch (Exception e) {
										LogManager.LogEA(className, ViewUtils.getErrorMessage(e));
									}
								}
							});
							
						} catch (Exception e1) {
							LogManager.LogEA(className, ViewUtils.getErrorMessage(e1));
							
						}
					}
				});
			} catch (Exception e) {
				LogManager.LogEA(className, ViewUtils.getErrorMessage(e));
				final String error = e.getMessage();
				final String string = "Request Top 100...";

				handleMessage(error, string);
				RatingActivity.this.runOnUiThread(new Runnable() {
					public void run() {
						ratingListView.setAdapter(null);
					}
				});
				return CODE_ERROR;
			}
		
			return CODE_OK;
		}

		@Override
		protected void onPostExecute(Integer _result) {
			super.onPostExecute(_result);
			if(_menu != null){
				MenuItem menuItem = _menu.findItem(R.id.action_share);
				ShareActionProvider actionProvider = (ShareActionProvider) menuItem.getActionProvider();
				actionProvider.setOnShareTargetSelectedListener(RatingActivity.this);	
				actionProvider.setShareIntent(getDefaultShareIntent());
			}
			
		}
	};
	
	void normalizeCurrentIndexCategory(){
		currentIndexCategory = (currentIndexCategory >= offsetIndexCategory && currentIndexCategory < categories.length +offsetIndexCategory) ? currentIndexCategory: offsetIndexCategory;
	}
	void normalizeCurrentIndexServer(){
		currentIndexServer = (currentIndexServer >= 0 && currentIndexServer < servers.length) ? currentIndexServer: 0;
		switch(currentIndexCategory){
		case TOP_100:
			currentIndexServer = (currentIndexServer >= 0 && currentIndexServer < servers.length) ? currentIndexServer: 0;
			break;
		case TOP_100_CLANS:
			currentIndexServer = (currentIndexServer >= offsetIndexServer && currentIndexServer < servers.length + offsetIndexServer) ? currentIndexServer: offsetIndexServer;
		
			break;
		};
	}
	void normalizeCurrentIndexClasses(){
		switch(currentIndexCategory){
		case TOP_100:
			classes = RatingActivity.this.getResources().getStringArray(R.array.classes_top100);
			currentIndexClass = (currentIndexClass>=0 && currentIndexClass < classes.length) ? currentIndexClass: 0;
		
			break;
		case TOP_100_CLANS:
			classes = RatingActivity.this.getResources().getStringArray(R.array.classes_top100_clans);
			currentIndexClass = (currentIndexClass >= offsetIndexClass && currentIndexClass < classes.length + offsetIndexClass) ? currentIndexClass: offsetIndexClass;
		
			break;
		};
	}
	
	public static void startTapFieldAnimation(View v) {
		v.clearAnimation();
		v.startAnimation(tapFieldAnimation);
	}
	
    private void expandList(boolean ok) {
        listExpanded = ok;
        LinearLayout buttonsLayout = (LinearLayout) findViewById(R.id.rating_activity_buttons_linear_layout);
        if(listExpanded) {
        	buttonsLayout.setVisibility(View.GONE);
        	expandListIndicator.setImageResource(R.drawable.list_arrow_down);
        } else {
        	buttonsLayout.setVisibility(View.VISIBLE);
        	expandListIndicator.setImageResource(R.drawable.list_arrow_up);
        }
    }

    private Menu _menu = null;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		try{
			getMenuInflater().inflate(R.menu.ratingactivity_menu, menu);
			
			MenuItem rateMenuItem = menu.add(Menu.NONE, R.id.action_rate, Menu.NONE, R.string.action_rate);
			rateMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
			Drawable iconRate = getResources().getDrawable(R.drawable.ic_thumbs_up);
			
			MenuItem updateMenuItem = menu.add(Menu.NONE, R.id.action_update, Menu.NONE, R.string.action_update);
			updateMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
			Drawable iconUpdate = getResources().getDrawable(R.drawable.widget_update_icon);
			
			MenuItem shareMenuItem = menu.add(Menu.NONE, R.id.action_share,
					Menu.NONE, R.string.action_share);
			shareMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
			Drawable iconShare = getResources().getDrawable(android.R.drawable.ic_menu_share);
			ShareActionProvider actionProvider = new ShareActionProvider(this);
		
			
			actionProvider.setShareHistoryFileName("ratingactivity_share.xml");
			shareMenuItem.setActionProvider(actionProvider);
			
			
			// FIXME: getAction().getHeight get null when rotate screen Android
			// 4.1.2
			if (getActionBar().getHeight() != 0) {
				this.heightActionBar = getActionBar().getHeight();
			}
	
			rateMenuItem.setIcon(ViewUtils.scaleImage(
					iconRate, this.heightActionBar));
			updateMenuItem.setIcon(ViewUtils.scaleImage(
					iconUpdate, this.heightActionBar ));
			shareMenuItem.setIcon(ViewUtils.scaleImage(
					iconShare, this.heightActionBar));
			
			_menu = menu;
			return super.onCreateOptionsMenu(menu);
		}
		catch(Exception e){
			LogManager.LogEA(className, ViewUtils.getErrorMessage(e));
		}
		return false;
	}

	  private Intent getDefaultShareIntent(){
		  try {
	        Intent intent = new Intent(Intent.ACTION_SEND);
	        intent.setType("text/plain");
	        intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share_with_help) + " "+ getString(R.string.app_name));
	       
			String message = 
					String.format("%s\n%s\n\n%s%s\n%s\n\n%s\n", 
						 getString(R.string.app_name),
						WidgetApplication.MARKET_LINK,			
						(currentIndexCategory == TOP_100)? classButton.getText() + "\n":"", 
						serverButton.getText(), 
						categoryButton.getText(),
						dateTextView.getText());
			
			for(int i=0 ; i< 5; i++){
				ListViewItem item = null;
				
				switch(currentIndexCategory){
				case TOP_100:
					
					item = (Top100Item)ratingListView.getAdapter().getItem(i);
					
					message += String.format(
							"%s. %s %s%% %s;\n", 
							i + 1, 
							Html.fromHtml(((Top100Item) item).getNickname()), 
							((Top100Item) item).getProgress(),
							classes[((Top100Item) item).getClasstime()].toLowerCase(Locale.getDefault())
						);
					item = null;
					break;
				case TOP_100_CLANS:
					item = (Top100ClansItem)ratingListView.getAdapter().getItem(i);
					
					message += String.format(
							"%s. %s %s %s/%s;\n", 
							i + 1, 
							((Top100ClansItem) item).getClanName(), 
							((Top100ClansItem) item).getOwnerNickname(),
							((Top100ClansItem) item).getPos2(),
							((Top100ClansItem) item).getPos3()
						);
					item = null;
					break;
				}
			}
			
			intent.putExtra(Intent.EXTRA_TEXT, message);
		   
			LogManager.LogV(NewsActivity.className, LogManager.getExecuteMethodName(), intent, message);
	        
	        return intent;
		  } catch (NumberFormatException e) {
			  LogManager.LogEA(className, ViewUtils.getErrorMessage(e));
			
			} catch (Exception e) {
				LogManager.LogEA(className, ViewUtils.getErrorMessage(e));
				
			}
		  return null;
	    }
    
	@Override
	public void onProgress(TaskProgress message) {
	}

	@Override
	public void onComplete(String className, Object... params) {
		
	}

	@Override
	public void onCanceled(String className, Object... params) {
	}

	@Override
	public void handleMessage(String error, String string) {
		LogManager.LogEA(className, error, string);
			
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putBoolean(RatingActivity.LIST_EXPANDED_INTENT, this.listExpanded);
		outState.putInt(NewsActivity.KEY_HEIGHT_ACTION_BAR,
				this.heightActionBar);
		super.onSaveInstanceState(outState);
	}

	@Override
	public boolean onShareTargetSelected(ShareActionProvider source,
			Intent intent) {
		LogManager.LogEA(className, intent);
		source.setShareIntent(getDefaultShareIntent());
	
		return false;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case R.id.action_rate:
			Intent goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse(WidgetApplication.MARKET_URI));
			startActivity(goToMarket);
		
			return true;
			
		case R.id.action_update:
			rebuildList(true);
			return true;
		
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void handleError(String title, String string) {
		// TODO Auto-generated method stub
		
	}
}